package com.ljx.config;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.PriorityOrdered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * Company: 上海数惠系统技术有限公司
 * Department: 数据中心：研发二部
 * Date: 2021/04/12 09:00
 *
 * @Author: Ljxpa
 * Email: lujx@dist.com.cn
 * Desc:
 */
@Aspect
@Component
@Order(1)
public class SwitchDatasourceAop {

	@Pointcut(value = "@annotation(com.ljx.config.SwitchDatasource)")
	public void pt(){
	}

	@Around(value = "pt() && @annotation(SwitchDatasource)")
	public Object around(ProceedingJoinPoint pjp) throws Throwable {
		MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
		Method targetMethod = methodSignature.getMethod();
		if (targetMethod.isAnnotationPresent(SwitchDatasource.class)) {
			DatasourceTypeEnum targetDataSource = targetMethod.getAnnotation(SwitchDatasource.class).dataSource();
			System.out.println("----------数据源是:" + targetDataSource + "------");
			DatasourceContextHolder.setReadOrWrite(targetDataSource);
		}
		// 执行方法
		Object result = pjp.proceed();
		DatasourceContextHolder.clearLocal();
		return result;
	}
}
